<template>
  <div class="household-list-container">
    <el-card class="household-card">
      <template #header>
        <div class="card-header">
          <span>房屋管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增房屋
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="所属社区">
            <el-select
              v-model="searchForm.communityId"
              placeholder="请选择社区"
              clearable
              style="width: 200px"
              @change="handleCommunityChange"
            >
              <el-option
                v-for="item in communityOptions"
                :key="item.id"
                :label="item.communityName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属楼栋">
            <el-select
              v-model="searchForm.buildingId"
              placeholder="请选择楼栋"
              clearable
              style="width: 200px"
              @change="handleBuildingChange"
            >
              <el-option
                v-for="item in filteredBuildingOptions"
                :key="item.id"
                :label="item.buildingName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属单元">
            <el-select
              v-model="searchForm.unitId"
              placeholder="请选择单元"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="item in unitOptions"
                :key="item.id"
                :label="item.unitName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房屋号">
            <el-input
              v-model="searchForm.roomNumber"
              placeholder="请输入房间号"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="房屋状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="空闲" :value="0" />
              <el-option label="已入住" :value="1" />
              <el-option label="已售" :value="2" />
              <el-option label="已租" :value="3" />
              <el-option label="装修中" :value="4" />
            </el-select>
          </el-form-item>
          
          <!-- 第二行搜索条件 -->
          <el-form-item label="房屋类型">
            <el-select v-model="searchForm.roomType" placeholder="请选择房屋类型" clearable style="width: 150px">
              <el-option label="一室" :value="1" />
              <el-option label="两室" :value="2" />
              <el-option label="三室" :value="3" />
              <el-option label="四室及以上" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="装修状态">
            <el-select v-model="searchForm.decorationStatus" placeholder="请选择装修状态" clearable style="width: 150px">
              <el-option label="毛坯" :value="0" />
              <el-option label="简装" :value="1" />
              <el-option label="精装" :value="2" />
              <el-option label="豪华装修" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="产权类型">
            <el-select v-model="searchForm.propertyType" placeholder="请选择产权类型" clearable style="width: 150px">
              <el-option label="商品房" :value="1" />
              <el-option label="经济适用房" :value="2" />
              <el-option label="公租房" :value="3" />
              <el-option label="其他" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="面积范围">
            <el-input
              v-model="searchForm.areaMin"
              placeholder="最小面积"
              clearable
              style="width: 100px"
            />
            <span style="margin: 0 8px">-</span>
            <el-input
              v-model="searchForm.areaMax"
              placeholder="最大面积"
              clearable
              style="width: 100px"
            />
          </el-form-item>
          
          <!-- 第三行搜索条件 -->
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入房屋号或房户编码"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.createTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格区域 -->
      <div class="table-area" v-if="!showEmptyState">
        <el-table
          v-loading="loading"
          :data="filteredTableData"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="roomNumber" label="房屋号" width="100" />
          <el-table-column prop="buildingName" label="所属楼栋" min-width="120" />
          <el-table-column prop="unitName" label="所属单元" width="100" />
          <el-table-column prop="area" label="面积(㎡)" width="100" align="center" />
          <el-table-column prop="roomType" label="房屋类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getRoomTypeTagType(row.roomType)))" size="small">
                {{ getRoomTypeText(row.roomType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="hallCount" label="客厅数" width="80" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getStatusTagType(row.status)))">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="roomType" label="房屋类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getHouseTypeTagType(row.roomType)))" size="small">
                {{ getHouseTypeText(row.roomType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="decorationStatus" label="装修状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="String(getTagType(getDecorationTagType(row.decorationStatus)))" size="small">
                {{ getDecorationText(row.decorationStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" text @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="success" size="small" text @click="handleView(row)">
                查看详情
              </el-button>
              <el-button type="danger" size="small" text @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-area" v-if="filteredTableData.length > 0">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-state" v-if="showEmptyState">
        <el-empty
          :description="emptyStateMessage"
          :image-size="200"
        >
          <template #description>
            <div class="empty-description">
              <p>{{ emptyStateMessage }}</p>
              <p class="empty-sub-description">{{ emptyStateDescription }}</p>
            </div>
          </template>
          <template #extra>
            <div class="empty-actions">
              <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增房屋
              </el-button>
            </div>
          </template>
        </el-empty>
      </div>
    </el-card>
    

    
    <!-- 房屋详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="房屋详情"
      width="95%"
      top="5vh"
      :before-close="handleDetailClose"
      class="household-detail-dialog"
    >
      <div v-if="currentHouseholdDetail" class="household-detail">
        <!-- 房屋详情信息 -->
        <el-card class="detail-card" shadow="never">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="房屋编码">{{ currentHouseholdDetail.householdCode }}</el-descriptions-item>
            <el-descriptions-item label="房间号">{{ currentHouseholdDetail.roomNumber }}</el-descriptions-item>
            <el-descriptions-item label="所属社区">{{ currentHouseholdDetail.communityName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="所属楼栋">{{ currentHouseholdDetail.buildingName }}</el-descriptions-item>
            <el-descriptions-item label="所属单元">{{ currentHouseholdDetail.unitName }}</el-descriptions-item>
            <el-descriptions-item label="楼层号">{{ currentHouseholdDetail.floorNumber }}</el-descriptions-item>
            <el-descriptions-item label="面积">{{ currentHouseholdDetail.area }}㎡</el-descriptions-item>
            <el-descriptions-item label="使用面积">{{ currentHouseholdDetail.usableArea }}㎡</el-descriptions-item>
            <el-descriptions-item label="朝向">{{ currentHouseholdDetail.orientation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="房间类型">
              <el-tag :type="getTagType(getRoomTypeTagType(currentHouseholdDetail.roomType))" size="small">
                {{ getRoomTypeText(currentHouseholdDetail.roomType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="客厅数">{{ currentHouseholdDetail.hallCount || '-' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getTagType(getStatusTagType(currentHouseholdDetail.status))">
                {{ getStatusText(currentHouseholdDetail.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="房屋类型">
              <el-tag :type="getTagType(getHouseTypeTagType(currentHouseholdDetail.roomType))" size="small">
                {{ getHouseTypeText(currentHouseholdDetail.roomType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="物业费标准">{{ currentHouseholdDetail.propertyFeeRate }}元/㎡</el-descriptions-item>
            <el-descriptions-item label="装修状态">
              <el-tag :type="getTagType(getDecorationTagType(currentHouseholdDetail.decorationStatus))" size="small">
                {{ getDecorationText(currentHouseholdDetail.decorationStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="排序">{{ currentHouseholdDetail.sortOrder }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentHouseholdDetail.createTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ currentHouseholdDetail.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentHouseholdDetail.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- Tab页内容 -->
        <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card">
            <!-- 业主Tab -->
            <el-tab-pane label="业主" name="owner">
              <div class="tab-content">
                <el-table
                  :data="ownerList"
                  border
                  stripe
                  v-loading="tabLoading.owner"
                  style="width: 100%"
                >
                  <el-table-column prop="ownerName" label="业主姓名" min-width="120" />
                  <el-table-column prop="phone" label="联系电话" min-width="140" />
                  <el-table-column prop="idCard" label="身份证号" min-width="180" />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getOwnerStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div class="pagination-area" v-if="ownerList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.owner.current"
                    v-model:page-size="tabPagination.owner.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.owner.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('owner', size)"
                    @current-change="(current) => handleTabCurrentChange('owner', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 家庭成员Tab -->
            <el-tab-pane label="家庭成员" name="family">
              <div class="tab-content">
                <el-table
                  :data="familyList"
                  border
                  stripe
                  v-loading="tabLoading.family"
                  style="width: 100%"
                >
                  <el-table-column prop="realName" label="姓名" min-width="100" />
                  <el-table-column prop="phone" label="联系电话" min-width="120" />
                  <el-table-column prop="identityNo" label="身份证号" min-width="180" />
                  <el-table-column prop="residentTypeName" label="身份" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getResidentTypeTagType(row.residentType)">
                        {{ row.residentTypeName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="moveInDate" label="入住日期" min-width="120" />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getResidentStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div class="pagination-area" v-if="familyList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.family.current"
                    v-model:page-size="tabPagination.family.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.family.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('family', size)"
                    @current-change="(current) => handleTabCurrentChange('family', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 车辆Tab -->
            <el-tab-pane label="车辆" name="vehicle">
              <div class="tab-content">
                <el-table
                  :data="vehicleList"
                  border
                  stripe
                  v-loading="tabLoading.vehicle"
                  style="width: 100%"
                >
                  <el-table-column prop="plateNumber" label="车牌号" min-width="120" />
                  <el-table-column prop="vehicleType" label="车辆类型" min-width="100" />
                  <el-table-column prop="brand" label="品牌" min-width="100" />
                  <el-table-column prop="model" label="型号" min-width="120" />
                  <el-table-column prop="color" label="颜色" min-width="80" />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getVehicleStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div v-if="vehicleList.length === 0 && !tabLoading.vehicle" class="empty-state">
                  <el-empty description="暂无数据" />
                </div>
                <div class="pagination-area" v-if="vehicleList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.vehicle.current"
                    v-model:page-size="tabPagination.vehicle.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.vehicle.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('vehicle', size)"
                    @current-change="(current) => handleTabCurrentChange('vehicle', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 租客Tab -->
            <el-tab-pane label="租客" name="tenant">
              <div class="tab-content">
                <el-table
                  :data="tenantList"
                  border
                  stripe
                  v-loading="tabLoading.tenant"
                  style="width: 100%"
                >
                  <el-table-column prop="realName" label="租客姓名" min-width="120" />
                  <el-table-column prop="phone" label="联系电话" min-width="140" />
                  <el-table-column prop="identityNo" label="身份证号" min-width="180" />
                  <el-table-column prop="contractStartDate" label="合同开始日期" min-width="140" />
                  <el-table-column prop="contractEndDate" label="合同结束日期" min-width="140" />
                  <el-table-column prop="monthlyRent" label="月租金" min-width="100" />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getTenantStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div class="pagination-area" v-if="tenantList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.tenant.current"
                    v-model:page-size="tabPagination.tenant.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.tenant.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('tenant', size)"
                    @current-change="(current) => handleTabCurrentChange('tenant', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 车位Tab -->
            <el-tab-pane label="车位" name="parking">
              <div class="tab-content">
                <el-table
                  :data="parkingList"
                  border
                  stripe
                  v-loading="tabLoading.parking"
                  style="width: 100%"
                >
                  <el-table-column prop="parkingNumber" label="车位号" min-width="100" />
                  <el-table-column prop="parkingType" label="车位类型" min-width="100" />
                  <el-table-column prop="area" label="面积" min-width="80" />
                  <el-table-column prop="monthlyFee" label="月租费" min-width="100" />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getParkingStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div v-if="parkingList.length === 0 && !tabLoading.parking" class="empty-state">
                  <el-empty description="暂无数据" />
                </div>
                <div class="pagination-area" v-if="parkingList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.parking.current"
                    v-model:page-size="tabPagination.parking.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.parking.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('parking', size)"
                    @current-change="(current) => handleTabCurrentChange('parking', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 报修Tab -->
            <el-tab-pane label="报修" name="repair">
              <div class="tab-content">
                <el-table
                  :data="repairList"
                  border
                  stripe
                  v-loading="tabLoading.repair"
                  style="width: 100%"
                >
                  <el-table-column prop="repairTitle" label="报修标题" min-width="150" />
                  <el-table-column prop="repairType" label="报修类型" min-width="100" />
                  <el-table-column prop="description" label="问题描述" min-width="200" show-overflow-tooltip />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getRepairStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div class="pagination-area" v-if="repairList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.repair.current"
                    v-model:page-size="tabPagination.repair.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.repair.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('repair', size)"
                    @current-change="(current) => handleTabCurrentChange('repair', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 投诉Tab -->
            <el-tab-pane label="投诉" name="complaint">
              <div class="tab-content">
                <el-table
                  :data="complaintList"
                  border
                  stripe
                  v-loading="tabLoading.complaint"
                  style="width: 100%"
                >
                  <el-table-column prop="complaintTitle" label="投诉标题" min-width="150" />
                  <el-table-column prop="complaintType" label="投诉类型" min-width="100" />
                  <el-table-column prop="description" label="投诉内容" min-width="200" show-overflow-tooltip />
                  <el-table-column prop="statusName" label="状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getComplaintStatusTagType(row.status)">
                        {{ row.statusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div v-if="complaintList.length === 0 && !tabLoading.complaint" class="empty-state">
                  <el-empty description="暂无数据" />
                </div>
                <div class="pagination-area" v-if="complaintList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.complaint.current"
                    v-model:page-size="tabPagination.complaint.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.complaint.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('complaint', size)"
                    @current-change="(current) => handleTabCurrentChange('complaint', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 物业费Tab -->
            <el-tab-pane label="物业费" name="propertyFee">
              <div class="tab-content">
                <el-table
                  :data="propertyFeeList"
                  border
                  stripe
                  v-loading="tabLoading.propertyFee"
                  style="width: 100%"
                >
                  <el-table-column prop="billingPeriod" label="费用周期" min-width="120" />
                  <el-table-column prop="amount" label="费用金额" min-width="100" />
                  <el-table-column prop="paymentStatusName" label="缴费状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                        {{ row.paymentStatusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div class="pagination-area" v-if="propertyFeeList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.propertyFee.current"
                    v-model:page-size="tabPagination.propertyFee.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.propertyFee.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('propertyFee', size)"
                    @current-change="(current) => handleTabCurrentChange('propertyFee', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 卫生费Tab -->
            <el-tab-pane label="卫生费" name="sanitationFee">
              <div class="tab-content">
                <el-table
                  :data="sanitationFeeList"
                  border
                  stripe
                  v-loading="tabLoading.sanitationFee"
                  style="width: 100%"
                >
                  <el-table-column prop="billingPeriod" label="费用周期" min-width="120" />
                  <el-table-column prop="amount" label="费用金额" min-width="100" />
                  <el-table-column prop="paymentStatusName" label="缴费状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                        {{ row.paymentStatusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div class="pagination-area" v-if="sanitationFeeList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.sanitationFee.current"
                    v-model:page-size="tabPagination.sanitationFee.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.sanitationFee.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('sanitationFee', size)"
                    @current-change="(current) => handleTabCurrentChange('sanitationFee', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 燃气费Tab -->
            <el-tab-pane label="燃气费" name="gasFee">
              <div class="tab-content">
                <el-table
                  :data="gasFeeList"
                  border
                  stripe
                  v-loading="tabLoading.gasFee"
                  style="width: 100%"
                >
                  <el-table-column prop="billingPeriod" label="费用周期" min-width="120" />
                  <el-table-column prop="amount" label="费用金额" min-width="100" />
                  <el-table-column prop="paymentStatusName" label="缴费状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                        {{ row.paymentStatusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div v-if="gasFeeList.length === 0 && !tabLoading.gasFee" class="empty-state">
                  <el-empty description="暂无数据" />
                </div>
                <div class="pagination-area" v-if="gasFeeList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.gasFee.current"
                    v-model:page-size="tabPagination.gasFee.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.gasFee.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('gasFee', size)"
                    @current-change="(current) => handleTabCurrentChange('gasFee', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 水费Tab -->
            <el-tab-pane label="水费" name="waterFee">
              <div class="tab-content">
                <el-table
                  :data="waterFeeList"
                  border
                  stripe
                  v-loading="tabLoading.waterFee"
                  style="width: 100%"
                >
                  <el-table-column prop="billingPeriod" label="费用周期" min-width="120" />
                  <el-table-column prop="amount" label="费用金额" min-width="100" />
                  <el-table-column prop="paymentStatusName" label="缴费状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                        {{ row.paymentStatusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div v-if="waterFeeList.length === 0 && !tabLoading.waterFee" class="empty-state">
                  <el-empty description="暂无数据" />
                </div>
                <div class="pagination-area" v-if="waterFeeList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.waterFee.current"
                    v-model:page-size="tabPagination.waterFee.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.waterFee.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('waterFee', size)"
                    @current-change="(current) => handleTabCurrentChange('waterFee', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
            
            <!-- 电费Tab -->
            <el-tab-pane label="电费" name="electricFee">
              <div class="tab-content">
                <el-table
                  :data="electricFeeList"
                  border
                  stripe
                  v-loading="tabLoading.electricFee"
                  style="width: 100%"
                >
                  <el-table-column prop="billingPeriod" label="费用周期" min-width="120" />
                  <el-table-column prop="amount" label="费用金额" min-width="100" />
                  <el-table-column prop="paymentStatusName" label="缴费状态" min-width="100">
                    <template #default="{ row }">
                      <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                        {{ row.paymentStatusName }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                  <el-table-column prop="createTime" label="创建时间" min-width="160" />
                </el-table>
                <div v-if="electricFeeList.length === 0 && !tabLoading.electricFee" class="empty-state">
                  <el-empty description="暂无数据" />
                </div>
                <div class="pagination-area" v-if="electricFeeList.length > 0">
                  <el-pagination
                    v-model:current-page="tabPagination.electricFee.current"
                    v-model:page-size="tabPagination.electricFee.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="tabPagination.electricFee.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="(size) => handleTabSizeChange('electricFee', size)"
                    @current-change="(current) => handleTabCurrentChange('electricFee', current)"
                  />
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 房屋管理页面
 * @author Wu.Liang
 * @date 2024-12-21
 */
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Search, Refresh, Message, Delete } from '@element-plus/icons-vue'
import { householdApi } from '@/api/household'
import { buildingApi } from '@/api/building'
import { communityApi } from '@/api/community'
import { unitApi } from '@/api/unit'
import { residentApi } from '@/api/resident'
import { repairOrderApi as repairApi } from '@/api/repair'
import { propertyFeeApi } from '@/api/property/propertyFee'
import { sanitationFeeApi } from '@/api/property/sanitationFee'
import { HouseholdStatus, RoomType, DecorationStatus } from '@/types/region'
import { hasPermission, getDataScopeText, getDataScopeTagType } from '@/utils/permission'
import { showMessage, getTagType } from '@/utils/message'

import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'

// 初始化router
const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref<any[]>([])

const detailVisible = ref(false)

const currentHouseholdDetail = ref<any>(null)
const buildingOptions = ref<any[]>([])
const communityOptions = ref<any[]>([])
const unitOptions = ref<any[]>([])

// 住户相关数据
const residentList = ref<any[]>([])
const residentLoading = ref(false)
const residentPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// Tab页相关数据
const activeTab = ref('owner')

// Tab页数据列表
const ownerList = ref<any[]>([])
const familyList = ref<any[]>([])
const vehicleList = ref<any[]>([])
const tenantList = ref<any[]>([])
const parkingList = ref<any[]>([])
const repairList = ref<any[]>([])
const complaintList = ref<any[]>([])
const propertyFeeList = ref<any[]>([])
const sanitationFeeList = ref<any[]>([])
const gasFeeList = ref<any[]>([])
const waterFeeList = ref<any[]>([])
const electricFeeList = ref<any[]>([])

// Tab页加载状态
const tabLoading = reactive({
  owner: false,
  family: false,
  vehicle: false,
  tenant: false,
  parking: false,
  repair: false,
  complaint: false,
  propertyFee: false,
  sanitationFee: false,
  gasFee: false,
  waterFee: false,
  electricFee: false
})

// Tab页分页数据
const tabPagination = reactive({
  owner: { current: 1, size: 10, total: 0 },
  family: { current: 1, size: 10, total: 0 },
  vehicle: { current: 1, size: 10, total: 0 },
  tenant: { current: 1, size: 10, total: 0 },
  parking: { current: 1, size: 10, total: 0 },
  repair: { current: 1, size: 10, total: 0 },
  complaint: { current: 1, size: 10, total: 0 },
  propertyFee: { current: 1, size: 10, total: 0 },
  sanitationFee: { current: 1, size: 10, total: 0 },
  gasFee: { current: 1, size: 10, total: 0 },
  waterFee: { current: 1, size: 10, total: 0 },
  electricFee: { current: 1, size: 10, total: 0 }
})

// 初始化权限信息，防止未定义报错
const userPermissionInfo = ref<{
  isSuperAdmin: boolean
  hasPropertyCompany: boolean
  propertyCompanyId: number | null
  propertyCompanyName: string
}>({
  isSuperAdmin: false,
  hasPropertyCompany: false,
  propertyCompanyId: null,
  propertyCompanyName: ''
})

// 加载用户权限信息
const loadUserPermissionInfo = async () => {
  console.log('loadUserPermissionInfo 被调用')
  try {
    const userStore = useUserStore()
    // 首先确保公司信息是最新的
    await userStore.checkAndUpdateCompanyInfo()
    
    const permission = await userStore.getUserDataScope()
    userPermissionInfo.value.isSuperAdmin = permission.isSuperAdmin
    userPermissionInfo.value.hasPropertyCompany = permission.hasPropertyCompany
    userPermissionInfo.value.propertyCompanyId = permission.companyId
    userPermissionInfo.value.propertyCompanyName = permission.companyName
  } catch (error) {
    console.error('加载用户权限信息失败:', error)
    userPermissionInfo.value.isSuperAdmin = false
    userPermissionInfo.value.hasPropertyCompany = false
    userPermissionInfo.value.propertyCompanyId = null
    userPermissionInfo.value.propertyCompanyName = ''
  }
}

// 搜索表单
const searchForm = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  roomNumber: '',
  roomType: undefined as number | undefined,
  decorationStatus: undefined as number | undefined,
  propertyType: undefined as number | undefined,
  status: undefined as number | undefined,
  areaMin: undefined as number | undefined,
  areaMax: undefined as number | undefined,
  keyword: '',
  createTimeRange: null as [string, string] | null
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 状态映射
const statusMap: Record<number, { text: string; type: string }> = {
  [HouseholdStatus.VACANT]: { text: '空闲', type: 'info' },
  [HouseholdStatus.OCCUPIED]: { text: '已入住', type: 'success' },
  [HouseholdStatus.RENTED]: { text: '已租', type: 'primary' },
  [HouseholdStatus.DECORATING]: { text: '装修中', type: 'danger' }
}

const houseTypeMap: Record<number, { text: string; type: string }> = {
  [RoomType.ONE_ROOM]: { text: '一室', type: 'info' },
  [RoomType.TWO_ROOM]: { text: '两室', type: 'success' },
  [RoomType.THREE_ROOM]: { text: '三室', type: 'warning' },
  [RoomType.FOUR_PLUS]: { text: '四室及以上', type: 'danger' }
}

const decorationMap: Record<number, { text: string; type: string }> = {
  [DecorationStatus.ROUGH]: { text: '毛坯', type: 'info' },
  [DecorationStatus.SIMPLE]: { text: '简装', type: 'warning' },
  [DecorationStatus.FINE]: { text: '精装', type: 'success' },
  [DecorationStatus.LUXURY]: { text: '豪装', type: 'danger' }
}

const roomTypeMap: Record<number, { text: string; type: string }> = {
  1: { text: '一室', type: 'info' },
  2: { text: '两室', type: 'success' },
  3: { text: '三室', type: 'warning' },
  4: { text: '四室及以上', type: 'danger' }
}

// 权限判断computed
const isSuperAdmin = computed(() => {
  return userPermissionInfo.value.isSuperAdmin
})

const hasPropertyCompany = computed(() => {
  return userPermissionInfo.value.hasPropertyCompany
})

const canManage = computed(() => isSuperAdmin.value || hasPropertyCompany.value)

// 权限提示相关计算属性
const showPermissionTip = computed(() => {
  return !isSuperAdmin.value
})

const permissionTipTitle = computed(() => {
  return '数据权限说明'
})

const permissionTipDescription = computed(() => {
  return '您当前只能查看权限范围内的房屋数据。如需查看更多数据，请联系管理员申请权限。'
})

const permissionTipType = computed(() => {
  return 'info' as const
})

// 数据权限兼容兜底方法
const getUserDataScopeArray = () => {
  // 兼容后端未返回 dataScope 字段的情况，全部数据权限
  return ['ALL']
}
const userDataScopeInfo = computed(() => getDataScopeText(getUserDataScopeArray()))
const getDataScopeTagTypeComputed = computed(() => getDataScopeTagType(getUserDataScopeArray()))

// 空状态相关计算属性
const showEmptyState = computed(() => {
  return !isSuperAdmin.value && (!filteredTableData.value || filteredTableData.value.length === 0)
})

const emptyStateMessage = computed(() => {
  if (isSuperAdmin.value) {
    return '暂无房屋数据'
  }
  return '暂无权限访问房屋数据'
})

const emptyStateDescription = computed(() => {
  if (isSuperAdmin.value) {
    return '当前没有房屋数据，您可以点击下方按钮新增房屋'
  }
  return '您当前没有房屋数据的访问权限，请联系管理员申请权限'
})

// 数据权限过滤
const filteredTableData = computed((): any[] => {
  return Array.isArray(tableData.value) ? tableData.value : []
})

const filteredBuildingOptions = computed((): any[] => {
  return Array.isArray(buildingOptions.value) ? buildingOptions.value : []
})

// 操作权限相关计算属性
const canView = computed(() => {
  // 可根据实际权限判断逻辑调整
  return isSuperAdmin.value || hasPropertyCompany.value
})
const canDelete = computed(() => {
  // 可根据实际权限判断逻辑调整
  return isSuperAdmin.value || hasPropertyCompany.value
})

// 获取状态文本
const getStatusText = (status: number) => {
  return statusMap[status]?.text || '未知'
}

// 获取状态标签样式
const getStatusTagType = (status: number) => {
  return statusMap[status]?.type || 'info'
}

// 获取房屋类型文本
const getHouseTypeText = (roomType: number) => {
  return houseTypeMap[roomType]?.text || '未知'
}

// 获取房屋类型标签样式
const getHouseTypeTagType = (roomType: number) => {
  return houseTypeMap[roomType]?.type || 'info'
}

// 获取装修状态文本
const getDecorationText = (status: number) => {
  return decorationMap[status]?.text || '未知'
}

// 获取装修状态标签样式
const getDecorationTagType = (status: number) => {
  return decorationMap[status]?.type || 'info'
}

// 获取房间类型文本
const getRoomTypeText = (roomType: number) => {
  return roomTypeMap[roomType]?.text || '未知'
}

// 获取房间类型标签样式
const getRoomTypeTagType = (roomType: number) => {
  return roomTypeMap[roomType]?.type || 'info'
}

// 联系管理员
const handleContactAdmin = () => {
  showMessage({ type: 'info', message: '请联系系统管理员申请房屋数据访问权限' })
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 社区变化处理
const handleCommunityChange = async (communityId: number) => {
  searchForm.buildingId = undefined
  searchForm.unitId = undefined
  buildingOptions.value = []
  unitOptions.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      // 过滤掉没有有效id的数据
      buildingOptions.value = (response.data || []).filter((item: any) => item.id != null)
    } catch (error) {
      showMessage({ type: 'error', message: '加载楼栋数据失败' })
      buildingOptions.value = []
    }
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number) => {
  searchForm.unitId = undefined
  unitOptions.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      // 过滤掉没有有效id的数据
      unitOptions.value = (response.data || []).filter((item: any) => item.id != null)
    } catch (error) {
      showMessage({ type: 'error', message: '加载单元数据失败' })
      unitOptions.value = []
    }
  }
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    roomNumber: '',
    roomType: undefined,
    decorationStatus: undefined,
    propertyType: undefined,
    status: undefined,
    areaMin: undefined,
    areaMax: undefined,
    keyword: '',
    createTimeRange: null
  })
  buildingOptions.value = []
  unitOptions.value = []
  handleSearch()
}

// 加载数据
const loadData = async () => {
  console.log('loadData 被调用')
  try {
    loading.value = true
    const params: any = {
      current: pagination.current,
      size: pagination.size
    }
    
    // 只添加有值的搜索条件
    if (searchForm.communityId !== undefined) {
      params.communityId = searchForm.communityId
    }
    if (searchForm.buildingId !== undefined) {
      params.buildingId = searchForm.buildingId
    }
    if (searchForm.unitId !== undefined) {
      params.unitId = searchForm.unitId
    }
    if (searchForm.roomNumber) {
      params.roomNumber = searchForm.roomNumber
    }
    if (searchForm.roomType !== undefined) {
      params.roomType = searchForm.roomType
    }
    if (searchForm.decorationStatus !== undefined) {
      params.decorationStatus = searchForm.decorationStatus
    }
    if (searchForm.propertyType !== undefined) {
      params.propertyType = searchForm.propertyType
    }
    if (searchForm.status !== undefined) {
      params.status = searchForm.status
    }
    if (searchForm.areaMin !== undefined) {
      params.areaMin = searchForm.areaMin
    }
    if (searchForm.areaMax !== undefined) {
      params.areaMax = searchForm.areaMax
    }
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }
    if (searchForm.createTimeRange && searchForm.createTimeRange.length === 2) {
      params.createTimeStart = searchForm.createTimeRange[0]
      params.createTimeEnd = searchForm.createTimeRange[1]
    }
    
    console.log('房屋API请求参数:', params)
    const response = await householdApi.getHouseholdPage(params)
    console.log('房屋API响应:', response)
    // 确保数据是数组格式
    tableData.value = Array.isArray(response.data?.records) ? response.data.records : []
    pagination.total = response.data?.total || 0
  } catch (error) {
    console.error('加载房屋列表失败:', error)
    showMessage({ type: 'error', message: '加载房屋列表失败' })
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 加载社区选项
const loadCommunityOptions = async () => {
  console.log('loadCommunityOptions 被调用')
  try {
    const response = await communityApi.getCommunityList({})
    console.log('社区API响应:', response)
    // 过滤掉没有有效id的数据
    communityOptions.value = (response.data || []).filter((item: any) => item.id != null)
  } catch (error) {
    console.error('加载社区数据失败:', error)
    showMessage({ type: 'error', message: '加载社区数据失败' })
    communityOptions.value = []
  }
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 新增房屋
const handleAdd = () => {
  router.push('/region/household/add')
}

// 编辑房屋
const handleEdit = async (row: any) => {
  // 跳转到编辑页面，传递房屋ID
  router.push(`/region/household/edit/${row.id}`)
}

// 查看房屋详情
const handleView = async (row: any) => {
  try {
    // 获取房屋详情
    const response = await householdApi.getHouseholdDetail(row.id)
    if (response.data) {
      currentHouseholdDetail.value = response.data
      detailVisible.value = true
      
      // 重置Tab页数据
      resetTabData()
      activeTab.value = 'owner'
      
      // 加载第一个Tab页的数据
      await loadTabData('owner')
    } else {
      showMessage({ type: 'error', message: '获取房屋详情失败' })
    }
  } catch (error) {
    console.error('获取房屋详情失败:', error)
    showMessage({ type: 'error', message: '获取房屋详情失败' })
  }
}

// 加载住户列表
const loadResidentList = async (householdId: number) => {
  try {
    residentLoading.value = true
    const params = {
      current: residentPagination.current,
      size: residentPagination.size,
      householdId: householdId
    }
    
    const response = await residentApi.getResidentList(params)
    residentList.value = Array.isArray(response.data?.records) ? response.data.records : []
    residentPagination.total = response.data?.total || 0
  } catch (error) {
    console.error('加载住户列表失败:', error)
    showMessage({ type: 'error', message: '加载住户列表失败' })
    residentList.value = []
    residentPagination.total = 0
  } finally {
    residentLoading.value = false
  }
}

// 住户分页处理
const handleResidentSizeChange = (size: number) => {
  residentPagination.size = size
  residentPagination.current = 1
  if (currentHouseholdDetail.value && currentHouseholdDetail.value.id) {
    loadResidentList(currentHouseholdDetail.value.id)
  }
}

const handleResidentCurrentChange = (current: number) => {
  residentPagination.current = current
  if (currentHouseholdDetail.value && currentHouseholdDetail.value.id) {
    loadResidentList(currentHouseholdDetail.value.id)
  }
}



// 删除住户
const handleDeleteResident = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '确认移除该住户吗？此操作不可恢复。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await residentApi.removeResidentFromHousehold(
      currentHouseholdDetail.value.id,
      row.residentId
    )
    showMessage({ type: 'success', message: '移除成功' })
    loadResidentList(currentHouseholdDetail.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除住户失败:', error)
      showMessage({ type: 'error', message: '移除住户失败' })
    }
  }
}

// 关闭详情弹窗
const handleDetailClose = () => {
  detailVisible.value = false
  currentHouseholdDetail.value = null
  residentList.value = []
  residentPagination.current = 1
  residentPagination.total = 0
  
  // 重置Tab页数据
  activeTab.value = 'owner'
  resetTabData()
}

// 重置Tab页数据
const resetTabData = () => {
  ownerList.value = []
  familyList.value = []
  vehicleList.value = []
  tenantList.value = []
  parkingList.value = []
  repairList.value = []
  complaintList.value = []
  propertyFeeList.value = []
  sanitationFeeList.value = []
  gasFeeList.value = []
  waterFeeList.value = []
  electricFeeList.value = []
  
  // 重置分页数据
  Object.keys(tabPagination).forEach(key => {
    tabPagination[key].current = 1
    tabPagination[key].total = 0
  })
  
  // 重置加载状态
  Object.keys(tabLoading).forEach(key => {
    tabLoading[key] = false
  })
}

// Tab页点击处理
const handleTabClick = (tab: any) => {
  console.log('Tab点击事件触发，tab对象:', tab)
  console.log('tab.name:', tab?.name)
  console.log('tab.paneName:', tab?.paneName)
  
  // 尝试多种方式获取tab名称
  const tabName = tab?.name || tab?.paneName || tab?.props?.name
  console.log('获取到的tabName:', tabName)
  
  // 防止重复调用：如果当前已经是这个Tab页，则不重复加载
  if (tabName && activeTab.value !== tabName) {
    activeTab.value = tabName
    console.log('切换到Tab页:', tabName)
    // 直接调用数据加载，不使用setTimeout避免重复调用
    loadTabData(tabName)
  } else if (tabName && activeTab.value === tabName) {
    console.log('Tab页已经是当前页，跳过重复加载:', tabName)
  } else {
    console.log('无法获取tab名称，tab对象:', tab)
  }
}

// 加载Tab页数据
const loadTabData = async (tabName: string) => {
  console.log('loadTabData被调用，tabName:', tabName)
  if (!currentHouseholdDetail.value?.id) {
    console.log('没有房屋详情，无法加载Tab页数据')
    return
  }
  
  const householdId = currentHouseholdDetail.value.id
  console.log('房屋ID:', householdId)
  
  switch (tabName) {
    case 'owner':
      await loadOwnerList(householdId)
      break
    case 'family':
      await loadFamilyList(householdId)
      break
    case 'vehicle':
      await loadVehicleList(householdId)
      break
    case 'tenant':
      await loadTenantList(householdId)
      break
    case 'parking':
      await loadParkingList(householdId)
      break
    case 'repair':
      await loadRepairList(householdId)
      break
    case 'complaint':
      await loadComplaintList(householdId)
      break
    case 'propertyFee':
      await loadPropertyFeeList(householdId)
      break
    case 'sanitationFee':
      await loadSanitationFeeList(householdId)
      break
    case 'gasFee':
      await loadGasFeeList(householdId)
      break
    case 'waterFee':
      await loadWaterFeeList(householdId)
      break
    case 'electricFee':
      await loadElectricFeeList(householdId)
      break
  }
}

// 加载业主列表
const loadOwnerList = async (householdId: number) => {
  try {
    tabLoading.owner = true
    const response = await householdApi.getHouseholdOwners(householdId, tabPagination.owner.current, tabPagination.owner.size)
    ownerList.value = response.data?.records || []
    tabPagination.owner.total = response.data?.total || 0
  } catch (error) {
    console.error('加载业主列表失败:', error)
    showMessage({ type: 'error', message: '加载业主列表失败' })
  } finally {
    tabLoading.owner = false
  }
}

// 加载家庭成员列表
const loadFamilyList = async (householdId: number) => {
  try {
    tabLoading.family = true
    const response = await householdApi.getHouseholdFamilyMembers(householdId, tabPagination.family.current, tabPagination.family.size)
    familyList.value = response.data?.records || []
    tabPagination.family.total = response.data?.total || 0
  } catch (error) {
    console.error('加载家庭成员列表失败:', error)
    showMessage({ type: 'error', message: '加载家庭成员列表失败' })
  } finally {
    tabLoading.family = false
  }
}

// 加载车辆列表
const loadVehicleList = async (householdId: number) => {
  console.log('loadVehicleList被调用，householdId:', householdId)
  try {
    tabLoading.vehicle = true
    // 静态数据 - 车辆信息
    const mockVehicleData = [
      {
        id: 1,
        plateNumber: '京A12345',
        vehicleType: '小型汽车',
        brand: '丰田',
        model: '凯美瑞',
        color: '白色',
        ownerName: '张三',
        phone: '13800138000',
        status: 1,
        statusName: '正常',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        plateNumber: '京B67890',
        vehicleType: '小型汽车',
        brand: '本田',
        model: '雅阁',
        color: '黑色',
        ownerName: '李四',
        phone: '13900139000',
        status: 1,
        statusName: '正常',
        createTime: '2024-02-20 14:20:00'
      }
    ]
    
    vehicleList.value = mockVehicleData
    tabPagination.vehicle.total = mockVehicleData.length
    console.log('车辆列表加载完成，数据量:', mockVehicleData.length)
  } catch (error) {
    console.error('加载车辆列表失败:', error)
    showMessage({ type: 'error', message: '加载车辆列表失败' })
  } finally {
    tabLoading.vehicle = false
  }
}

// 加载租客列表
const loadTenantList = async (householdId: number) => {
  try {
    tabLoading.tenant = true
    const response = await householdApi.getHouseholdTenants(householdId, tabPagination.tenant.current, tabPagination.tenant.size)
    tenantList.value = response.data?.records || []
    tabPagination.tenant.total = response.data?.total || 0
  } catch (error) {
    console.error('加载租客列表失败:', error)
    showMessage({ type: 'error', message: '加载租客列表失败' })
  } finally {
    tabLoading.tenant = false
  }
}

// 加载车位列表
const loadParkingList = async (householdId: number) => {
  try {
    tabLoading.parking = true
    // 静态数据 - 车位信息
    const mockParkingData = [
      {
        id: 1,
        parkingNumber: 'A001',
        parkingType: '地下车位',
        area: 12.5,
        status: 1,
        statusName: '已使用',
        ownerName: '张三',
        phone: '13800138000',
        startDate: '2024-01-01',
        endDate: '2024-12-31',
        createTime: '2024-01-01 09:00:00'
      },
      {
        id: 2,
        parkingNumber: 'A002',
        parkingType: '地下车位',
        area: 12.5,
        status: 1,
        statusName: '已使用',
        ownerName: '李四',
        phone: '13900139000',
        startDate: '2024-02-01',
        endDate: '2024-12-31',
        createTime: '2024-02-01 10:00:00'
      }
    ]
    
    parkingList.value = mockParkingData
    tabPagination.parking.total = mockParkingData.length
  } catch (error) {
    console.error('加载车位列表失败:', error)
    showMessage({ type: 'error', message: '加载车位列表失败' })
  } finally {
    tabLoading.parking = false
  }
}

// 加载报修列表
const loadRepairList = async (householdId: number) => {
  try {
    tabLoading.repair = true
    const response = await repairApi.getHouseholdRepairOrders(householdId, tabPagination.repair.current, tabPagination.repair.size)
    repairList.value = response.data?.records || []
    tabPagination.repair.total = response.data?.total || 0
  } catch (error) {
    console.error('加载报修列表失败:', error)
    showMessage({ type: 'error', message: '加载报修列表失败' })
  } finally {
    tabLoading.repair = false
  }
}

// 加载投诉列表
const loadComplaintList = async (householdId: number) => {
  try {
    tabLoading.complaint = true
    // 静态数据 - 投诉信息
    const mockComplaintData = [
      {
        id: 1,
        complaintNo: 'TS202401001',
        complaintType: '噪音投诉',
        complaintTitle: '楼上装修噪音过大',
        description: '楼上住户装修时间过长，影响正常休息',
        status: 1,
        statusName: '处理中',
        complainantName: '张三',
        complainantPhone: '13800138000',
        createTime: '2024-01-15 14:30:00'
      },
      {
        id: 2,
        complaintNo: 'TS202401002',
        complaintType: '环境卫生',
        complaintTitle: '楼道卫生问题',
        description: '楼道垃圾清理不及时，影响环境卫生',
        status: 2,
        statusName: '已处理',
        complainantName: '李四',
        complainantPhone: '13900139000',
        createTime: '2024-01-20 10:15:00'
      }
    ]
    
    complaintList.value = mockComplaintData
    tabPagination.complaint.total = mockComplaintData.length
  } catch (error) {
    console.error('加载投诉列表失败:', error)
    showMessage({ type: 'error', message: '加载投诉列表失败' })
  } finally {
    tabLoading.complaint = false
  }
}

// 加载物业费列表
const loadPropertyFeeList = async (householdId: number) => {
  try {
    tabLoading.propertyFee = true
    const response = await propertyFeeApi.getHouseholdPropertyFees(householdId, tabPagination.propertyFee.current, tabPagination.propertyFee.size)
    propertyFeeList.value = response.data?.records || []
    tabPagination.propertyFee.total = response.data?.total || 0
  } catch (error) {
    console.error('加载物业费列表失败:', error)
    showMessage({ type: 'error', message: '加载物业费列表失败' })
  } finally {
    tabLoading.propertyFee = false
  }
}

// 加载卫生费列表
const loadSanitationFeeList = async (householdId: number) => {
  try {
    tabLoading.sanitationFee = true
    const response = await sanitationFeeApi.getHouseholdSanitationFees(householdId, tabPagination.sanitationFee.current, tabPagination.sanitationFee.size)
    sanitationFeeList.value = response.data?.records || []
    tabPagination.sanitationFee.total = response.data?.total || 0
  } catch (error) {
    console.error('加载卫生费列表失败:', error)
    showMessage({ type: 'error', message: '加载卫生费列表失败' })
  } finally {
    tabLoading.sanitationFee = false
  }
}

// 加载燃气费列表
const loadGasFeeList = async (householdId: number) => {
  try {
    tabLoading.gasFee = true
    // 静态数据 - 燃气费信息
    const mockGasFeeData = [
      {
        id: 1,
        billingPeriod: '2024年1月',
        amount: 85.50,
        paymentStatus: 1,
        paymentStatusName: '已缴费',
        dueDate: '2024-02-15',
        paidDate: '2024-02-10',
        createTime: '2024-01-01 00:00:00'
      },
      {
        id: 2,
        billingPeriod: '2024年2月',
        amount: 92.30,
        paymentStatus: 0,
        paymentStatusName: '未缴费',
        dueDate: '2024-03-15',
        createTime: '2024-02-01 00:00:00'
      }
    ]
    
    gasFeeList.value = mockGasFeeData
    tabPagination.gasFee.total = mockGasFeeData.length
  } catch (error) {
    console.error('加载燃气费列表失败:', error)
    showMessage({ type: 'error', message: '加载燃气费列表失败' })
  } finally {
    tabLoading.gasFee = false
  }
}

// 加载水费列表
const loadWaterFeeList = async (householdId: number) => {
  try {
    tabLoading.waterFee = true
    // 静态数据 - 水费信息
    const mockWaterFeeData = [
      {
        id: 1,
        billingPeriod: '2024年1月',
        amount: 45.80,
        paymentStatus: 1,
        paymentStatusName: '已缴费',
        dueDate: '2024-02-15',
        paidDate: '2024-02-12',
        createTime: '2024-01-01 00:00:00'
      },
      {
        id: 2,
        billingPeriod: '2024年2月',
        amount: 52.60,
        paymentStatus: 0,
        paymentStatusName: '未缴费',
        dueDate: '2024-03-15',
        createTime: '2024-02-01 00:00:00'
      }
    ]
    
    waterFeeList.value = mockWaterFeeData
    tabPagination.waterFee.total = mockWaterFeeData.length
  } catch (error) {
    console.error('加载水费列表失败:', error)
    showMessage({ type: 'error', message: '加载水费列表失败' })
  } finally {
    tabLoading.waterFee = false
  }
}

// 加载电费列表
const loadElectricFeeList = async (householdId: number) => {
  try {
    tabLoading.electricFee = true
    // 静态数据 - 电费信息
    const mockElectricFeeData = [
      {
        id: 1,
        billingPeriod: '2024年1月',
        amount: 128.50,
        paymentStatus: 1,
        paymentStatusName: '已缴费',
        dueDate: '2024-02-15',
        paidDate: '2024-02-08',
        createTime: '2024-01-01 00:00:00'
      },
      {
        id: 2,
        billingPeriod: '2024年2月',
        amount: 145.80,
        paymentStatus: 0,
        paymentStatusName: '未缴费',
        dueDate: '2024-03-15',
        createTime: '2024-02-01 00:00:00'
      }
    ]
    
    electricFeeList.value = mockElectricFeeData
    tabPagination.electricFee.total = mockElectricFeeData.length
  } catch (error) {
    console.error('加载电费列表失败:', error)
    showMessage({ type: 'error', message: '加载电费列表失败' })
  } finally {
    tabLoading.electricFee = false
  }
}

// Tab页分页处理
const handleTabSizeChange = (tabName: string, size: number) => {
  tabPagination[tabName].size = size
  tabPagination[tabName].current = 1
  loadTabData(tabName)
}

const handleTabCurrentChange = (tabName: string, current: number) => {
  tabPagination[tabName].current = current
  loadTabData(tabName)
}

// 获取住户身份标签样式
const getResidentTypeTagType = (type: number) => {
  switch (type) {
    case 1: return 'success' // 户主
    case 2: return 'info'    // 家庭成员
    case 3: return 'warning' // 租客
    case 4: return 'danger'  // 临时居住
    default: return 'info'   // 默认使用info类型
  }
}

// 获取住户状态标签样式
const getResidentStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常居住
    case 0: return 'danger'  // 已搬出
    case 2: return 'warning' // 暂时外出
    default: return 'info'   // 默认使用info类型
  }
}

// 获取业主状态标签样式
const getOwnerStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常
    case 0: return 'danger'  // 禁用
    default: return 'info'   // 默认使用info类型
  }
}

// 获取车辆状态标签样式
const getVehicleStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常
    case 0: return 'danger'  // 禁用
    default: return 'info'   // 默认使用info类型
  }
}

// 获取租客状态标签样式
const getTenantStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常
    case 0: return 'danger'  // 已搬出
    default: return 'info'   // 默认使用info类型
  }
}

// 获取车位状态标签样式
const getParkingStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 正常
    case 0: return 'danger'  // 禁用
    default: return 'info'   // 默认使用info类型
  }
}

// 获取报修状态标签样式
const getRepairStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'warning' // 待处理
    case 2: return 'info'    // 处理中
    case 3: return 'success' // 已完成
    case 0: return 'danger'  // 已取消
    default: return 'info'   // 默认使用info类型
  }
}

// 获取投诉状态标签样式
const getComplaintStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'warning' // 待处理
    case 2: return 'info'    // 处理中
    case 3: return 'success' // 已完成
    case 0: return 'danger'  // 已取消
    default: return 'info'   // 默认使用info类型
  }
}

// 获取缴费状态标签样式
const getPaymentStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success' // 已缴费
    case 0: return 'danger'  // 未缴费
    case 2: return 'warning' // 部分缴费
    default: return 'info'   // 默认使用info类型
  }
}

// 删除房屋
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房屋"${row.roomNumber}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await householdApi.deleteHousehold(row.id)
    showMessage({ type: 'success', message: '删除成功' })
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}



// 初始化数据
const initData = async () => {
  console.log('initData 被调用')
  try {
    // 并行加载权限信息和业务数据，互不依赖
    await Promise.all([
      loadUserPermissionInfo(), // 权限信息用于按钮显示
      loadCommunityOptions(), // 社区选项
    ]);
    
    // 房屋列表和楼栋选项在社区加载完成后加载
    loadData(); // 房屋列表
  } catch (error) {
    console.error('初始化数据失败:', error);
    showMessage({ type: 'error', message: '初始化数据失败' });
  }
};

// 组件挂载时初始化
onMounted(() => {
  console.log('HouseholdList 组件挂载')
  initData();
});
</script>

<style lang="scss" scoped>
.household-list-container {
  padding: 20px;
  
  .household-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .permission-tip {
      margin-bottom: 20px;
      
      .permission-info {
        .data-scope-info {
          margin: 10px 0;
          
          span {
            margin-right: 10px;
            color: #606266;
          }
        }
        
        .contact-admin {
          margin-top: 10px;
        }
      }
    }
    
    .search-area {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }
    
    .table-area {
      .pagination-area {
        margin-top: 20px;
        text-align: right;
      }
    }
    
    .empty-state {
      min-height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .empty-description {
        .empty-sub-description {
          margin-top: 10px;
          color: #909399;
          font-size: 14px;
        }
      }
      
      .empty-actions {
        margin-top: 20px;
        display: flex;
        gap: 10px;
        justify-content: center;
      }
    }
  }
}

// 房屋详情弹窗样式
:deep(.household-detail-dialog) {
  .el-dialog__body {
    padding: 20px;
    max-height: 80vh;
    overflow-y: auto;
  }
  
  .household-detail {
    .detail-card {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .tab-content {
      min-height: 400px;
      
      .pagination-area {
        margin-top: 20px;
        text-align: right;
      }
    }
  }
}

// Tab页样式优化
:deep(.el-tabs--card) {
  .el-tabs__header {
    margin: 0 0 20px 0;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .el-tabs__nav {
    border: none;
  }
  
  .el-tabs__item {
    border: 1px solid #e4e7ed;
    border-bottom: none;
    border-radius: 4px 4px 0 0;
    margin-right: 4px;
    padding: 0 20px;
    height: 40px;
    line-height: 40px;
    background-color: #f5f7fa;
    color: #606266;
    transition: all 0.3s;
    
    &:hover {
      color: #409eff;
      background-color: #ecf5ff;
    }
    
    &.is-active {
      background-color: #fff;
      color: #409eff;
      border-bottom: 1px solid #fff;
      position: relative;
      z-index: 1;
    }
  }
  
  .el-tabs__content {
    padding: 0;
  }
}

// 表格样式优化
:deep(.el-table) {
  .el-table__header {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }
  
  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}

// 分页样式优化
:deep(.el-pagination) {
  .el-pagination__total {
    color: #606266;
    font-weight: 500;
  }
  
  .el-pagination__jump {
    color: #606266;
  }
}
</style> 